<template>
  <div>
    <h2>ML.NET 模型预测</h2>
    <form @submit.prevent="submitPrediction">
      <label>
        月份 (格式: YYYY-MM-DD):
        <input v-model="formData.Month" type="text" required />
      </label>
      <br />
      <label>
        是否周末 (0或1):
        <input v-model="formData.Is_Weekend" type="number" required />
      </label>
      <br />
      <label>
        用户ID:
        <input v-model="formData.User_ID" type="number" required />
      </label>
      <br />
      <button type="submit" :disabled="loading">进行预测</button>
    </form>

    <div v-if="loading">正在预测...</div>
    <div v-if="predictionResult !== null">
      <p>预测结果: {{ predictionResult }}</p>
    </div>
    <div v-if="error">
      <p style="color: red;">错误: {{ error }}</p>
    </div>
  </div>
</template>

<script setup>
import http from '@/http/axiosHelper'
import { ref, reactive } from 'vue';
import axios from 'axios';

const formData = reactive({
  User_ID: 1, // 假设默认用户ID为1
  Month: '2025-08-01',
  Is_Weekend: 0
});

const predictionResult = ref(null);
const loading = ref(false);
const error = ref('');

const submitPrediction = async () => {
  loading.value = true;
  error.value = '';
  predictionResult.value = null;

  try {
    const url = 'http://localhost:5000/predict';

    // 构建 x-www-form-urlencoded 格式的字符串
    const body = new URLSearchParams();
    body.append('User_ID', formData.User_ID);
    body.append('Month', formData.Month);
    body.append('Is_Weekend', formData.Is_Weekend);

    const response = await axios.post(url, body, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    if (response.data.success) {
      predictionResult.value = response.data.predictedPurchase;
    } else {
      error.value = response.data.error || '预测失败';
    }
  } catch (err) {
    console.error('Prediction failed:', err);
    error.value = '请求出错，请检查后端服务是否已启动。';
  } finally {
    loading.value = false;
  }
};
</script>